<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="分类名称" prop="categoryName">
        <el-input
          v-model="queryParams.categoryName"
          placeholder="请输入分类名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['goods:category:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="Sort" @click="toggleExpandAll"
          >展开/折叠</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="categoryList"
      row-key="id"
      :default-expand-all="isExpandAll"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <el-table-column label="分类名称" align="center" prop="categoryName" />
      <el-table-column prop="categoryImg" label="分类图标" align="center" width="100">
        <template #default="scope">
          <ImagePreview
            :src="scope.row.categoryImg"
            :height="40"
            :width="40"
          ></ImagePreview>
        </template>
      </el-table-column>
      <el-table-column
        label="排序"
        align="center"
        prop="sortNum"
      />
      <el-table-column
        label="添加时间"
        align="center"
        width="160"
        prop="createTime"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['goods:category:edit']"
            >修改</el-button
          >
          <el-button link type="primary" icon="Plus" @click="handleAdd(scope.row)" v-hasPermi="['goods:category:add']">新增</el-button>
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['goods:category:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改商品分类对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form
        ref="goodsCategoryRef"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="上级分类">
          <el-tree-select
            style="width: 100%"
            v-model="form.parentId"
            :data="categoryOptions"
            :props="{
              value: 'id',
              label: 'categoryName',
              children: 'children',
            }"
            value-key="id"
            placeholder="选择上级分类"
            check-strictly
          />
        </el-form-item>
        <el-form-item label="分类名称" prop="categoryName">
          <el-input v-model="form.categoryName" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="图标" prop="categoryImg">
          <image-upload
            title="分类图标"
            v-model="form.categoryImg"
            :limit="1"
          />
        </el-form-item>
        <el-form-item label="排序" prop="sortNum">
          <el-input v-model="form.sortNum" placeholder="请输入排序号" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="goodsCategory">
import {
  listCategory,
  getCategory,
  delCategory,
  addCategory,
  updateCategory,
} from "@/api/goods/goodsCategory";

const { proxy } = getCurrentInstance();

// 遮罩层
const loading = ref(true);
// 选中数组
const ids = ref([]);
// 非单个禁用
const single = ref(true);
// 非多个禁用
const multiple = ref(true);
// 显示搜索条件
const showSearch = ref(true);
// 商品分类表格数据
const categoryList = ref([]);
// 商品分类树数据
const categoryOptions = ref([]);
const isExpandAll = ref(false);
const refreshTable = ref(true);
// 弹出层标题
const title = ref("");
// 是否显示弹出层
const open = ref(false);

const data = reactive({
  form: {},
  queryParams: {
    categoryName: null,
  },
  rules: {
    categoryName: [
      { required: true, message: "分类名称不能为空", trigger: "blur" },
    ],
    sortNum: [{ required: true, message: "分类顺序不能为空", trigger: "blur" }],
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 查询商品分类列表 */
const getList = () => {
  loading.value = true;
  listCategory(queryParams.value).then((response) => {
    categoryList.value = proxy.handleTree(response.data, "id");
    loading.value = false;
  });
};

/** 查询分类下拉树结构 */
function getTreeselect() {
  categoryOptions.value = [];
  listCategory().then((response) => {
    const tree = proxy.handleTree(response.data, "id");
    categoryOptions.value = tree;
  });
}

// 取消按钮
const cancel = () => {
  open.value = false;
  reset();
};

// 表单重置
const reset = () => {
  form.value = {
    id: null,
    parentId: null,
    ancestors: null,
    categoryName: null,
    categoryImg: null,
    sortNum: null,
    createBy: null,
    createId: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null,
  };
  proxy.resetForm("goodsCategoryRef");
};
/** 搜索按钮操作 */
const handleQuery = () => {
  getList();
};
/** 重置按钮操作 */
const resetQuery = () => {
  resetForm("queryForm");
  handleQuery();
};

/** 新增按钮操作 */
const handleAdd = (row) => {
  reset();
  getTreeselect();
  if (row != null && row.id) {
    form.value.parentId = row.id;
  } else {
    form.value.parentId = 0;
  }
  open.value = true;
  title.value = "添加商品分类";
};

/** 展开/折叠操作 */
function toggleExpandAll() {
  refreshTable.value = false;
  isExpandAll.value = !isExpandAll.value;
  nextTick(() => {
    refreshTable.value = true;
  });
}

/** 修改按钮操作 */
async function handleUpdate(row) {
  reset();
  await getTreeselect();
  const id = row.id || ids.value;
  getCategory(id).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改商品分类";
  });
}
/** 提交按钮 */
const submitForm = () => {
  proxy.$refs["goodsCategoryRef"].validate((valid) => {
    if (valid) {
      if (form.value.id != null) {
        updateCategory(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addCategory(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
};
/** 删除按钮操作 */
const handleDelete = (row) => {
  const ids = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除商品分类编号为"' + ids + '"的数据项？')
    .then(function () {
      return delCategory(ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
};
/** 导出按钮操作 */
const handleExport = () => {
  proxy.download(
    "goods/category/export",
    {
      ...queryParams.value,
    },
    `category_${new Date().getTime()}.xlsx`
  );
};

getList();
</script>
